#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Tabindex Template tag is used as a counter for tabindex attribute"""

from django import template
import re
import unicodedata
from django.utils.functional import allow_lazy
#from django.utils import six

register = template.Library()

#@register.simple_tag
def inc(arg=None):
    "Tag giving and autoincrementing infex useful e.g. for tabindex"
    try:
        if arg is not None:
            inc.increment = arg - 1
        inc.increment += 1
        return int(inc.increment)
    except (ValueError, TypeError):
        return 1
#inc.increment = 0

register.simple_tag(inc)


def incr(value, arg=None):
    "Filter increases the value by arg."

    try:
        if arg is not None:
            inc.increment = arg - 1
        incr.increment += 1
        return int(value) + int(incr.increment)
    except (ValueError, TypeError):
        try:
            return value + 1
        except StandardError as err:
            print err
            return value
incr.is_safe = False

register.filter(incr)


#==========================================================
def one_space(value):
    """
    Converts two or more whitespaces to a single space. A single tab or newline
    are left intact.
    """
    value = unicodedata.normalize('NFKD',
                               value).encode('ascii', 'ignore').decode('ascii')
    value = re.sub('\s\s+', ' ', value)
    return value
one_space.is_safe = False
#one_space = allow_lazy(one_space, six.text_type)

register.filter(one_space)
